<template>
  <view class="container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          v-model="keyword"
          placeholder="搜索零食"
          class="search-input"
          @confirm="search"
          @input="onInput"
          focus
        />
        <text v-if="keyword" class="clear-btn" @click="clearKeyword">×</text>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>

    <!-- 搜索历史 -->
    <view v-if="!keyword && searchHistory.length > 0" class="search-history">
      <view class="section-header">
        <text class="section-title">搜索历史</text>
        <text class="clear-history" @click="clearHistory">清空</text>
      </view>
      <view class="history-tags">
        <text 
          v-for="item in searchHistory" 
          :key="item"
          class="history-tag"
          @click="searchByHistory(item)"
        >
          {{ item }}
        </text>
      </view>
    </view>

    <!-- 热门搜索 -->
    <view v-if="!keyword" class="hot-search">
      <view class="section-header">
        <text class="section-title">热门搜索</text>
      </view>
      <view class="hot-tags">
        <text 
          v-for="tag in hotTags" 
          :key="tag.id"
          class="hot-tag"
          @click="searchByTag(tag.name)"
        >
          {{ tag.name }}
        </text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view v-if="keyword && !loading" class="search-results">
      <view class="result-header">
        <text class="result-count">找到 {{ totalCount }} 个商品</text>
        <view class="sort-buttons">
          <text 
            class="sort-btn"
            :class="{ active: sortType === 'default' }"
            @click="changeSort('default')"
          >综合</text>
          <text 
            class="sort-btn"
            :class="{ active: sortType === 'price' }"
            @click="changeSort('price')"
          >价格</text>
          <text 
            class="sort-btn"
            :class="{ active: sortType === 'sales' }"
            @click="changeSort('sales')"
          >销量</text>
        </view>
      </view>

      <view v-if="products.length > 0" class="product-list">
        <product-card 
          v-for="product in products"
          :key="product.id"
          :product="product"
          @cart-updated="onCartUpdated"
        />
      </view>

      <view v-else class="no-results">
        <image src="/static/images/no-results.png" class="no-results-image" mode="aspectFit" />
        <text class="no-results-text">没有找到相关商品</text>
        <text class="no-results-desc">试试其他关键词吧</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>搜索中...</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !loading && products.length > 0" class="load-more" @click="loadMore">
      <text>加载更多</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { productApi } from '@/api/index.js';
import common from '@/utils/common.js';
import storage from '@/utils/storage.js';
import ProductCard from '@/components/product-card.vue';

// 响应式数据
const keyword = ref('');
const searchHistory = ref([]);
const hotTags = ref([]);
const products = ref([]);
const totalCount = ref(0);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(10);
const sortType = ref('default');
const searchTimer = ref(null);

// 加载搜索历史
const loadSearchHistory = () => {
  searchHistory.value = storage.getSearchHistory();
};

// 加载热门标签
const loadHotTags = async () => {
  try {
    const res = await productApi.getPopularTags();
    hotTags.value = res.data || [];
  } catch (error) {
    console.error('加载热门标签失败:', error);
  }
};

// 输入处理
const onInput = () => {
  // 防抖搜索
  if (searchTimer.value) {
    clearTimeout(searchTimer.value);
  }
  
  if (keyword.value.trim()) {
    searchTimer.value = setTimeout(() => {
      search();
    }, 500);
  } else {
    products.value = [];
    totalCount.value = 0;
  }
};

// 清空关键词
const clearKeyword = () => {
  keyword.value = '';
  products.value = [];
  totalCount.value = 0;
};

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 通过历史记录搜索
const searchByHistory = (keyword2) => {
  keyword.value = keyword2;
  search();
};

// 通过标签搜索
const searchByTag = (tagName) => {
  keyword.value = tagName;
  search();
};

// 搜索
const search = async () => {
  if (!keyword.value.trim()) return;

  try {
    loading.value = true;
    page.value = 1;
    hasMore.value = true;

    const params = {
      keyword: keyword.value.trim(),
      page: page.value,
      pageSize: pageSize.value
    };

    // 添加排序参数
    if (sortType.value === 'price') {
      params.sortBy = 'price';
      params.sortOrder = 'asc';
    } else if (sortType.value === 'sales') {
      params.sortBy = 'salesCount';
      params.sortOrder = 'desc';
    }

    const res = await productApi.searchProducts(keyword.value.trim(), params);
    products.value = res.data.items || [];
    totalCount.value = res.data.total || 0;
    hasMore.value = products.value.length === pageSize.value;

    // 保存搜索历史
    if (keyword.value.trim()) {
      storage.addSearchHistory(keyword.value.trim());
      loadSearchHistory();
    }
  } catch (error) {
    console.error('搜索失败:', error);
    common.showError('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 改变排序
const changeSort = (newSortType) => {
  if (sortType.value === newSortType) return;
  
  sortType.value = newSortType;
  search();
};

// 加载更多
const loadMore = async () => {
  if (loading.value || !hasMore.value) return;

  try {
    loading.value = true;
    page.value++;

    const params = {
      keyword: keyword.value.trim(),
      page: page.value,
      pageSize: pageSize.value
    };

    // 添加排序参数
    if (sortType.value === 'price') {
      params.sortBy = 'price';
      params.sortOrder = 'asc';
    } else if (sortType.value === 'sales') {
      params.sortBy = 'salesCount';
      params.sortOrder = 'desc';
    }

    const res = await productApi.searchProducts(keyword.value.trim(), params);
    const newProducts = res.data.items || [];
    
    products.value = [...products.value, ...newProducts];
    hasMore.value = newProducts.length === pageSize.value;
  } catch (error) {
    console.error('加载更多失败:', error);
    common.showError('加载失败');
    page.value--; // 恢复页码
  } finally {
    loading.value = false;
  }
};

// 清空历史
const clearHistory = () => {
  storage.clearSearchHistory();
  searchHistory.value = [];
};

// 购物车更新事件
const onCartUpdated = () => {
  // 购物车更新事件处理
};

// 生命周期
onMounted(() => {
  loadSearchHistory();
  loadHotTags();
  
  // 获取URL参数中的关键词
  const query = uni.getSystemInfoSync().platform === 'devtools' 
    ? getCurrentPages()[getCurrentPages().length - 1].options 
    : getCurrentPages()[getCurrentPages().length - 1].$page.options;
    
  if (query && query.keyword) {
    keyword.value = decodeURIComponent(query.keyword);
    search();
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}

.search-header {
  background: #fff;
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.search-input-wrapper {
  flex: 1;
  background: #f5f5f5;
  border-radius: 25rpx;
  padding: 15rpx 20rpx;
  display: flex;
  align-items: center;
}

.search-icon {
  margin-right: 10rpx;
  font-size: 28rpx;
  color: #999;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.clear-btn {
  font-size: 32rpx;
  color: #999;
  padding: 5rpx;
}

.cancel-btn {
  font-size: 28rpx;
  color: #666;
}

.search-history,
.hot-search {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.clear-history {
  font-size: 24rpx;
  color: #666;
}

.history-tags,
.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.history-tag,
.hot-tag {
  background: #f0f0f0;
  color: #666;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
}

.search-results {
  padding: 20rpx;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.result-count {
  font-size: 26rpx;
  color: #666;
}

.sort-buttons {
  display: flex;
  gap: 20rpx;
}

.sort-btn {
  font-size: 24rpx;
  color: #666;
  padding: 8rpx 16rpx;
  border-radius: 15rpx;
}

.sort-btn.active {
  background: #ff4757;
  color: #fff;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.no-results {
  text-align: center;
  padding: 100rpx 40rpx;
}

.no-results-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.no-results-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.no-results-desc {
  font-size: 26rpx;
  color: #666;
}

.loading,
.load-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
}

.load-more {
  cursor: pointer;
}
</style> 